import React, { useState, useEffect } from 'react';
import {
  UserOutlined, CalendarOutlined, ClockCircleOutlined, FileTextOutlined,
  PlusOutlined, SearchOutlined, BellOutlined, SettingOutlined, LogoutOutlined,
  BarChartOutlined, PieChartOutlined, AlertOutlined, CheckCircleOutlined
} from '@ant-design/icons';
import {
  Card, Button, Input, Badge, Avatar, Dropdown, Menu,
  Table, Tag, Space, Statistic, Spin, Empty, Divider, Progress,
  message
} from 'antd';
import 'antd/dist/reset.css';
import './MedicalConsole.css';
import type { Iganyuf } from '~/types/ganyuf';
import http from '~/api/http';
import { Link } from 'react-router';
import { useNavigate } from 'react-router-dom';


// 模拟医疗数据（保持不变）


    

const mockTodoData = [
  { id: 1, title: '审核5份住院病历报告', time: '今日15:00前', status: 'pending', progress: 0 },
  { id: 2, title: '心内科病例讨论（14:30）', time: '今日14:30', status: 'pending', progress: 0 },
  { id: 3, title: '跟进3位术后患者随访', time: '今日下班前', status: 'pending', progress: 0 },
  { id: 4, title: '更新科室医疗设备清单', time: '明日10:00前', status: 'pending', progress: 0 },
  { id: 5, title: '整理上月诊疗数据报表', time: '已完成', status: 'completed', progress: 100 },
];

const mockRecentPatients = [
  { id: 'P2025110501', name: '张三', gender: '男', age: 52, department: '心内科', diagnosis: '高血压2级', status: '待复诊' },
  { id: 'P2025110502', name: '李四', gender: '女', age: 36, department: '神经内科', diagnosis: '偏头痛', status: '就诊中' },
  { id: 'P2025110503', name: '王五', gender: '男', age: 68, department: '骨科', diagnosis: '腰椎间盘突出', status: '已出院' },
  { id: 'P2025110504', name: '赵六', gender: '女', age: 29, department: '妇产科', diagnosis: '孕期检查', status: '待就诊' },
];

const mockStatsData = [
  { title: '今日门诊量', value: 78, icon: <UserOutlined />, color: '#1890ff', trend: '诊量' },
  { title: '待诊患者', value: 15, icon: <ClockCircleOutlined />, color: '#faad14', trend: '待诊' },
  { title: '共完成诊疗', value: 63, icon: <CheckCircleOutlined />, color: '#52c41a', trend: '诊疗' },
  { title: '取消预约', value: 2, icon: <AlertOutlined />, color: '#ff4d4f', trend: '取消' },
];
const MedicalConsole = () => {
  const [loading, setLoading] = useState(true);
  const [todos, setTodos] = useState([]);
  const [patients, setPatients] = useState([]);

  const getRecentThreeDaysStart = () => {
  const now = new Date();
  // 计算「前天 00:00:00」的时间戳（最近3天 = 前天0点 到 今天24点）
  const threeDaysAgo = new Date(now);
  threeDaysAgo.setDate(now.getDate() - 2); // 减去2天（今天-0，昨天-1，前天-2）
  threeDaysAgo.setHours(0, 0, 0, 0); // 设为当天0点，避免时分秒干扰
  return threeDaysAgo.getTime(); // 返回毫秒级时间戳
};
const [searchValue, setSearchValue] = useState('');
// 2. 过滤逻辑（新增 u.sj 最近3天的判断）
const recentThreeDaysStart = getRecentThreeDaysStart();

const fetchUsers = async () => {
    try {
      const response = await http.getList<Iganyuf>('Order/chay', {});
      console.log("查询结果:", response.data);
      const bb = response.data.filter(u =>u.orderStatus === '正在体检'&&u.sj===currentYMD||u.orderStatus === '已完成'&&u.sj===currentYMD);
       const bb2 = response.data.filter(u =>u.orderStatus === '已预约'&&u.sj===currentYMD);
      const bb1 = response.data.filter(u =>u.orderStatus === '已完成');
       const bb5 = response.data.filter(u =>u.orderStatus === '已取消');
       const bb7 = response.data.filter(u =>u.orderStatus === '正在体检'&&u.sj===currentYMD)
setTodos(bb7);
      const bb3 = response.data.filter(u => {
  // 条件1：orderStatus 不等于「已取消」
  const isNotCanceled = u.orderStatus !== '已取消';
  // 条件2：u.sj 存在且在最近3天内
  const isInRecentThreeDays = () => {
    if (!u.sj) return false; // 无 sj 字段则过滤

    // 处理 u.sj 为「日期字符串」（如 "2025-11-05"、"2025-11-05 14:30:00"）
    let sjTimestamp;
    if (typeof u.sj === 'string') {
      sjTimestamp = new Date(u.sj).getTime();
    } else if (typeof u.sj === 'number') {
      // 处理 u.sj 为「时间戳」（毫秒级，如 1757000000000）
      sjTimestamp = u.sj;
    } else {
      return false; // 非字符串/数字格式则过滤
    }

    // 判断是否在「前天0点 - 今天24点」之间
    return !isNaN(sjTimestamp) && sjTimestamp >= recentThreeDaysStart;
  };

  // 两个条件同时满足才保留
  return isNotCanceled && isInRecentThreeDays();
});
setPatients(bb3);
console.log(bb3)
      mockStatsData[0].value=bb.length
       mockStatsData[2].value=bb1.length
       mockStatsData[1].value=bb2.length
       mockStatsData[3].value=bb5.length;
      if (bb.length > 0) {
        console.log("匹配结果:", bb[0]);        
      } else {
      
      }
    } catch (error) {
      console.error("查询失败:", error);
      message.error('查询失败，请稍后重试');
    }
  };
   // 1. 获取当前日期对象
  const now = new Date();
  
  // 2. 提取年月日（关键：月份+1，日期补零）
  const year = now.getFullYear(); // 年份（如 2025）
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份（0-11 → 补零为 01-12）
  const day = String(now.getDate()).padStart(2, '0'); // 日期（1-31 → 补零为 01-31）
  
  // 拼接为 YYYY-MM-DD 格式（接口常用）
  const currentYMD = `${year}-${month}-${day}`;
  useEffect(() => {
    console.log(currentYMD)
    fetchUsers()
    const timer = setTimeout(() => {
      
      
      setLoading(false);
    }, 600);
    return () => clearTimeout(timer);
  }, []);

 const cha=async ()=>{
  
   
      const response = await http.getList<Iganyuf>('Order/chay', {});
console.log('rr')
const bb3 = response.data.filter(u => {
  // 条件1：orderStatus 不等于「已取消」
  const isNotCanceled = u.orderStatus !== '已取消';
  const zz=u.name.includes(searchValue)
  // 条件2：u.sj 存在且在最近3天内
  const isInRecentThreeDays = () => {
    if (!u.sj) return false; // 无 sj 字段则过滤

    // 处理 u.sj 为「日期字符串」（如 "2025-11-05"、"2025-11-05 14:30:00"）
    let sjTimestamp;
    if (typeof u.sj === 'string') {
      sjTimestamp = new Date(u.sj).getTime();
    } else if (typeof u.sj === 'number') {
      // 处理 u.sj 为「时间戳」（毫秒级，如 1757000000000）
      sjTimestamp = u.sj;
    } else {
      return false; // 非字符串/数字格式则过滤
    }

    // 判断是否在「前天0点 - 今天24点」之间
    return !isNaN(sjTimestamp) && sjTimestamp >= recentThreeDaysStart;
  };

  // 两个条件同时满足才保留
  return isNotCanceled && zz&&isInRecentThreeDays();
});
   
setPatients(bb3);
  }
  // 用户菜单（保持不变）
  const userMenu = (
    <Menu>
      <Menu.Item key="1" icon={<UserOutlined />}>个人中心</Menu.Item>
      <Menu.Item key="2" icon={<SettingOutlined />}>系统设置</Menu.Item>
      <Menu.Divider />
      <Menu.Item key="3" icon={<LogoutOutlined />} danger>退出登录</Menu.Item>
    </Menu>
  );
  const navigate = useNavigate();
const dian=()=>{
navigate('/Users');
}
const dian1=()=>{
navigate('/Subscribe');
}
const dian2=()=>{
navigate('/appointment');
}
const dian3=()=>{
navigate('/ganyuf1');
}
const dian4=()=>{
navigate('/ganyuton');
}
  // 状态标签（缩小字体）
  const renderStatusTag = (orderStatus) => {
    switch (orderStatus) {
      case '待就诊':
        return <Tag color="gold" size="small">{orderStatus}</Tag>;
      case '正在体检':
        return <Tag color="blue" size="small">{orderStatus}</Tag>;
      case '已预约':
      case '已完成':
        return <Tag color="green" size="small">{orderStatus}</Tag>;
      case '未到诊':
        return <Tag color="orange" size="small">{orderStatus}</Tag>;
      case '紧急':
        return <Tag color="red" size="small">{orderStatus}</Tag>;
      default:
        return <Tag color="gray" size="small">{orderStatus}</Tag>;
    }
  };

  // 患者表格（缩小列宽、行高）
  const patientColumns = [
    { title: '预约号', dataIndex: 'hid', key: 'hid', width: 60 },
    { title: '会员编号', dataIndex: 'fileNumber', key: 'id', width: 100 },
    { title: '姓名', dataIndex: 'name', key: 'name', width: 80 },
    { title: '性别', dataIndex: 'sex', key: 'sex', width: 60 },
    { title: '年龄', dataIndex: 'age', key: 'age', width: 60 },
   { title: '预约时间', dataIndex: 'sj', key: 'sj', width: 80 },
    { 
      title: '状态', 
      dataIndex: 'orderStatus', 
      key: 'orderStatus', 
      width: 80,
      render: (orderStatus) => renderStatusTag(orderStatus)
    },
/*     {
      title: '操作',
      key: 'action',
      render: () => (
        <Space size="mini">
          <Button type="text" size="mini" style={{ color: '#1890ff' }}>详情</Button>
          <Button type="text" size="mini" style={{ color: '#faad14' }}>处理</Button>
        </Space>
      ),
    }, */
  ];

  // 切换待办状态（保持不变）


  return (
    <div className="medical-console">
      {/* 顶部导航栏（缩小高度、内边距） */}
      <header className="console-header">
        <div className="header-left">
          <div className="logo">
            <UserOutlined className="logo-icon" />
            <h1>医疗工作台</h1>
          </div>
        </div>

        <div className="header-right">
          <Input 
            className="search-input" 
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            placeholder="姓名/会员号" 
            prefix={<SearchOutlined />} 
            size="small" // 缩小输入框
          />
          
          <Badge onClick={cha} count={4} dot>
            <BellOutlined className="notification-icon" />
          </Badge>
          
          <Dropdown overlay={userMenu} placement="bottomRight">
            <div className="user-info">
              <Avatar size="small" src="https://via.placeholder.com/32" alt="医生头像" />
              <span className="user-name">李医生</span>
            </div>
          </Dropdown>
        </div>
      </header>

      {/* 数据概览区（缩小卡片间距） */}
      <div className="stats-grid">
        {mockStatsData.map((stat, index) => (
          <Card key={index} className="stat-card">
            <div className="stat-header">
              <span className="stat-title">{stat.title}</span>
              <div className="stat-icon" style={{ backgroundColor: `${stat.color}20`, color: stat.color }}>
                {stat.icon}
              </div>
            </div>
            <Statistic value={stat.value} className="stat-value" />
            <div className="stat-trend" style={{ color: stat.color }}>
              {stat.trend}
            </div>
          </Card>
        ))}
      </div>

      {/* 主要内容区（缩小间距） */}
      <div className="content-grid">
        <div className="left-column">
          <Card className="content-card" title="最近体检预约(三天)" extra={<Button type="text" size="mini" style={{ color: '#1890ff' }}>查看全部</Button>}>
            <Spin spinning={loading} tip="加载中..." size="small">
              {patients.length > 0 ? (
                <Table 
                  columns={patientColumns} 
                  dataSource={patients} 
                  rowKey="id" 
                  pagination={false} 
                  scroll={{ y: 220 }} // 缩小表格高度
                  className="patient-table"
                  size="small" // 缩小表格行高
                />
              ) : (
                <Empty description="暂无数据" size="small" />
              )}
            </Spin>
          </Card>

          <Card className="content-card todo-card" title="待办任务" >
            <div className="todo-list">
              {todos.map((todo) => (
                <div key={todo.id} className="todo-item">
                  <div className="todo-left">
                   
                    <div className="todo-info">
                      <div className="todo-title" >
                        预约号:{todo.hid}--
                        {todo.fileNumber}    {todo.name}
                      </div>
                      <div className="todo-time">{todo.sj}</div>
                    </div>
                  </div>
                 <Tag color="blue" size="small">{todo.orderStatus}</Tag>
                </div>
              ))}
            </div>
          </Card>
        </div>

        <div className="right-column">
          <Card className="content-card" title="快速操作">
            <div className="quick-actions">
              <Button onClick={dian1} className="action-btn" icon={<FileTextOutlined />} size="small">
                预约操作
              </Button>
              <Button onClick={dian2} className="action-btn" icon={<CalendarOutlined />} size="small">
                预约挂号
              </Button>
                
              <Button onClick={dian} className="action-btn" icon={<UserOutlined />} size="small">
                用户管理
              </Button>
            
              <Button onClick={dian3} className="action-btn" icon={<BarChartOutlined />} size="small">
                评估报表
              </Button>
              <Button onClick={dian4} className="action-btn" icon={<PieChartOutlined />} size="small">
                干预统计
              </Button>
              <Button className="action-btn" icon={<SettingOutlined />} size="small">
                系统设置
              </Button>
            </div>
          </Card>

          <Card className="content-card" title="诊疗进度">
            <div className="progress-container">
              <div className="progress-item">
                <span className="progress-label">门诊完成率</span>
                <Progress percent={75} strokeColor="#1890ff" className="progress-bar" size="small" />
                <span className="progress-value">75%</span>
              </div>
              <Divider style={{ margin: '8px 0' }} />
              <div className="progress-item">
                <span className="progress-label">病历审核率</span>
                <Progress percent={40} strokeColor="#faad14" className="progress-bar" size="small" />
                <span className="progress-value">40%</span>
              </div>
              <Divider style={{ margin: '8px 0' }} />
              <div className="progress-item">
                <span className="progress-label">随访完成率</span>
                <Progress percent={60} strokeColor="#52c41a" className="progress-bar" size="small" />
                <span className="progress-value">60%</span>
              </div>
            </div>
          </Card>
{/* 
          <Card className="content-card" title="系统通知">
            <div className="notification-list">
              <div className="notification-item">
                <AlertOutlined className="notification-tag" />
                <span className="notification-content">患者张三今日16:00复诊</span>
              </div>
              <div className="notification-item">
                <CheckCircleOutlined className="notification-tag success" />
                <span className="notification-content">3份病历报告已审核通过</span>
              </div>
              <div className="notification-item">
                <BellOutlined className="notification-tag warning" />
                <span className="notification-content">明日预约量已达上限</span>
              </div>
            </div>
          </Card> */}
        </div>
      </div>
    </div>
  );
};

export default MedicalConsole;